package com.vdong.trade.trading.service.impl;

import com.alibaba.fastjson.JSON;
import com.vdong.trade.trading.common.annotation.AmountLogAnnotation;
import com.vdong.trade.trading.common.constants.TradingConstants;
import com.vdong.trade.trading.common.exception.ServiceException;
import com.vdong.trade.trading.entity.dto.param.AmountDataDTO;
import com.vdong.trade.trading.entity.dto.param.AmountParamDTO;
import com.vdong.trade.trading.entity.dto.param.AmountTradingParamDTO;
import com.vdong.trade.trading.entity.dto.result.AmountResultDTO;
import com.vdong.trade.trading.entity.mo.AmountDataMO;
import com.vdong.trade.trading.entity.mo.AmountMO;
import com.vdong.trade.trading.facade.enums.StatusEnum;
import com.vdong.trade.trading.respository.AmountMORepository;
import com.vdong.trade.trading.service.AmountService;
import com.vdong.trade.trading.service.TradingService;
import lombok.extern.slf4j.Slf4j;
import org.lamb.framework.common.util.CopyUtil;
import org.lamb.framework.common.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.Optional;

/**
 * @author <a href="mailto:clf@vdongzc.com">clf</a>
 * @Description:用户资金service
 * @Date Create on 2018-12-13 15:10:22
 * @since version1.0
 */
@Service
@Slf4j
public class AmountServiceImpl implements AmountService {

    @Autowired
    private AmountMORepository amountMORepository;

    @Autowired
    private TradingService tradingService;


    @Override
    public AmountResultDTO selectAmountMOByUserId(Long userId, String userType) {
        log.info("selectAmountMOByUserId入参:userId=[{}],userType=[{}]", userId, userType);
        if (StringUtil.hasBlank(userId, userType)) {
            return null;
        }
        AmountMO selectAmountMO = new AmountMO();
        selectAmountMO.setUserId(userId);
        selectAmountMO.setUserType(userType);
        AmountMO amountMO = amountMORepository.selectAmountByEntity(selectAmountMO);

        if (StringUtil.hasBlank(amountMO)) {
            return null;
        }
        AmountResultDTO amountResultDTO = new AmountResultDTO();
        CopyUtil.copyObject(amountMO, amountResultDTO);
        return amountResultDTO;
    }

    @Override
    @AmountLogAnnotation
    public Optional<String> updateAmountByParam(AmountDataDTO param) {
        log.info("更新资金信息接口请求参数:[{}]", JSON.toJSONString(param));
        if (param == null) {
            return Optional.of("入参不能为空!");
        }

        if (StringUtil.hasBlank(param.getUserId()) && StringUtil.hasBlank(param.getUserType())) {
            return Optional.of("用户userId或账户类型userType不能为空!");
        }

        AmountDataMO amountDataMO = new AmountDataMO();
        CopyUtil.copyObject(param, amountDataMO);
        int count = amountMORepository.updateAmountByParam(amountDataMO);
        if (count < 1) {
            log.error("更新用户userId=[{}],userType=[{}] ==> 资金账户数据失败!", param.getUserId(), param.getUserType());
            return Optional.of("更新用户资金账户数据失败!");
        }
        return Optional.empty();
    }

    @Override
    public Optional<String> amountTrading(AmountTradingParamDTO param, Boolean flag) throws ServiceException {
        log.info("AmountService.amountTrading入参:[{}],flag:[{}]", JSON.toJSONString(param), flag);
        try {
            if (param == null) {
                return Optional.of("入参不能为空!");
            }
            // 更新账户信息
            AmountDataDTO dataDTO = new AmountDataDTO();
            CopyUtil.copyObject(param, dataDTO);
            Optional<String> optional = this.updateAmountByParam(dataDTO);
            if (optional.isPresent()) {
                return optional;
            }

            if (flag) {
                tradingService.insertTrading(param);
            }
        } catch (Exception e) {
            log.info("AmountService.amountTrading异常:", e);
            throw new ServiceException("更新用户资金账户或新增资金交易流水失败!");
        }
        return Optional.empty();
    }

    @Override
    public Optional<String> insertUserAmount(AmountParamDTO dto) {
        AmountMO amountMO = new AmountMO();
        amountMO.setUserId(dto.getUserId());
        amountMO.setUserType(dto.getUserType());
        amountMO.setStatus(Integer.valueOf(StatusEnum.STATUS_NO.getValue()));
        Integer count = amountMORepository.selectAmountCntByCond(amountMO);
        if (count > 0) {
            log.error("用户userId=[{}],userType=[{}]资金账户已存在,无需重复创建!", dto.getUserId(), dto.getUserType());
            return Optional.of("用户资金账户已存在,无需重复创建!");
        }

        amountMO.setCreateTime(new Date());
        amountMO.setUpdateTime(new Date());
        amountMO.setSettlementAmount(TradingConstants.INIT_USER_AMOUNT_MONEY);
        amountMO.setBalance(TradingConstants.INIT_USER_AMOUNT_MONEY);
        amountMO.setFrozenAmount(TradingConstants.INIT_USER_AMOUNT_MONEY);
        amountMO.setTotalWithdraw(TradingConstants.INIT_USER_AMOUNT_MONEY);

        amountMORepository.insertAmount(amountMO);
        return Optional.empty();
    }
}
